import { getProfileApi, getUserInfoApi, patchProfileApi } from '@/api/profile'
import type { User, Profile, ProfileParams } from '@/types/http'
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { removeTokenAsync } from './login'

const initialState = {
  user: {} as User,
  profile: {} as Profile
}

const profileSlice = createSlice({
  name: 'profile',
  initialState,
  reducers: {
  },
  extraReducers: (builder) => {
    builder.addCase(getUserInfoAsync.fulfilled, (state, action) => {
      state.user = action.payload
    })
    builder.addCase(getProfileAsync.fulfilled, (state, action) => {
      state.profile = action.payload
    })
    builder.addCase(logoutAsync.fulfilled, (state, action) => {
      return action.payload
    })
    builder.addCase(patchProfileAsync.fulfilled, (state, action) => {
      state.profile = {
        ...state.profile,
        ...action.payload
      }
    })
  }
})

// 异步获取个人信息
export const getUserInfoAsync = createAsyncThunk(
  'profile/getUserInfoAsync',
  async () => {
    const { data: { data: user } } = await getUserInfoApi()
    return user
  }
)

// 异步获取个人基本资料
export const getProfileAsync = createAsyncThunk(
  'profile/getProfileAsync',
  async () => {
    const { data: { data: profile } } = await getProfileApi()
    return profile
  }
)

// 退出
export const logoutAsync = createAsyncThunk(
  'profile/logoutAsync',
  (_, { dispatch }) => {
    dispatch(removeTokenAsync())
    return initialState
  }
)

export const patchProfileAsync = createAsyncThunk(
  'profile/patchProfileAsync',
  async (data: ProfileParams) => {
    await patchProfileApi(data)
    return data
  }
)

export default profileSlice.reducer